package jdbc.three.service.impl;

import jdbc.day2.demo4_对象工厂.ObjectFactory;
import jdbc.three.beans.Account;
import jdbc.three.dao.AccountDao;
import jdbc.three.exception.QueryMoneyEx;
import jdbc.three.exception.TransferEx;
import jdbc.three.service.AccountService;

import java.sql.SQLException;

public class AccountServiceImpl implements AccountService {
    AccountDao dao= (AccountDao) ObjectFactory.getObject("accountDaoImpl");
    @Override
    public boolean register(Account a) throws SQLException {
        try{
            return dao.insertAccount(a)>0;
        }catch (SQLException e){
            throw new SQLException("注册帐户失败");
        }
    }

    @Override
    public double queryMoney(int id) throws QueryMoneyEx {
        Account a=null;
        try {
            a=dao.selectById(id);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new QueryMoneyEx("查询余额失败");
        }
        return a==null?-1:a.getMoney();
    }

    @Override
    public boolean transferMoney(int from, int to, double m) throws TransferEx {
        try{
            Account f=dao.selectById(from);
            if(f.getMoney()<m){
                throw new TransferEx("钱不够转的");
            }

            Account t=dao.selectById(to);
            dao.updateById(from,f.getMoney()-m);
            dao.updateById(to,t.getMoney()+m);
        }catch (SQLException e){
            throw new TransferEx("转帐失败");
        }
        return true;
    }
}
